package com.cc.ttsreader

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import androidx.core.app.ActivityCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity

class PermissionFragment : Fragment() {
    var block: ((isEnale: Boolean) -> Unit)? = null
    var hasPermission: Boolean = true
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            hasPermission =
                activity?.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
            if (hasPermission) {
                block?.invoke(true)
                (activity as? FragmentActivity)?.supportFragmentManager?.popBackStack()
            } else {
                ActivityCompat.requestPermissions(
                    activity!!,
                    arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
                    1
                )
            }
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == 1) {
            block?.invoke(grantResults[0] == PackageManager.PERMISSION_GRANTED)
        }
    }

    fun check(activity: FragmentActivity) {
        activity.supportFragmentManager.beginTransaction().add(this, "")
            .addToBackStack("check")
            .commitAllowingStateLoss()
    }
}